import React, { useState, useEffect } from 'react';
import { Modal, Button, Radio, Space, Input, Tree, List, Spin } from 'antd';
import { SearchOutlined, CloseOutlined, CaretDownOutlined, CaretRightOutlined, LoadingOutlined } from '@ant-design/icons';
import KnowledgeBaseSelectModal from './KnowledgeBaseSelectModal';
import type { SelectionItem } from './ItemSelectionModal';
import type { DataNode } from 'antd/es/tree';

export interface UserWithPermission extends SelectionItem {
  permission?: string;
  allowedKnowledgeBases?: string[];
}

export interface UserPermissionSelectModalProps {
  visible: boolean;
  users: SelectionItem[];
  knowledgeBases: SelectionItem[];
  onCancel: () => void;
  onConfirm: (selectedUsers: UserWithPermission[]) => void;
  onLoadChildren?: (nodeId: string) => Promise<SelectionItem[]>;
}

const UserPermissionSelectModal: React.FC<UserPermissionSelectModalProps> = ({
  visible,
  users,
  knowledgeBases,
  onCancel,
  onConfirm,
  onLoadChildren
}) => {
  // 当前步骤：1-选择用户，2-权限设置
  const [currentStep, setCurrentStep] = useState<1 | 2>(1);
  // 选中的用户
  const [selectedUsers, setSelectedUsers] = useState<SelectionItem[]>([]);
  // 选中的用户ID
  const [selectedUserIds, setSelectedUserIds] = useState<string[]>([]);
  // 用户权限映射表
  const [userPermissions, setUserPermissions] = useState<Record<string, string>>({});
  // 用户可访问知识库映射表
  const [userKnowledgeBases, setUserKnowledgeBases] = useState<Record<string, string[]>>({});
  // 用户数据
  const [userData, setUserData] = useState<SelectionItem[]>([]);

  // 知识库选择模态框
  const [kbSelectVisible, setKbSelectVisible] = useState(false);
  // 当前正在编辑权限的用户ID
  const [currentEditingUserId, setCurrentEditingUserId] = useState<string>('');
  // 当前选中的知识库ID
  const [selectedKbIds, setSelectedKbIds] = useState<string[]>([]);

  // 用户选择相关状态
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const [loadingKeys, setLoadingKeys] = useState<string[]>([]);

  // 初始化用户数据
  useEffect(() => {
    setUserData(users);
  }, [users]);

  // 将数据转换为树节点格式
  const convertToTreeData = (items: SelectionItem[]): DataNode[] => {
    return items.map(item => ({
      key: item.id,
      title: item.name,
      children: item.children ? convertToTreeData(item.children) : undefined,
      isLeaf: item.children ? item.children.length === 0 : true
    }));
  };

  // 处理搜索
  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.trim();
    setSearchValue(value);

    if (value) {
      // 搜索时展开所有匹配的节点
      const matchedKeys: React.Key[] = [];
      const searchNodes = (nodes: SelectionItem[]) => {
        nodes.forEach(node => {
          if (node.name.toLowerCase().includes(value.toLowerCase())) {
            matchedKeys.push(node.id);
          }
          if (node.children) {
            searchNodes(node.children);
          }
        });
      };
      searchNodes(userData);
      setExpandedKeys(matchedKeys);
    } else {
      // 清空搜索时折叠所有节点
      setExpandedKeys([]);
    }
  };

  // 处理树形选择
  const handleTreeSelect = (checkedKeys: React.Key[] | { checked: React.Key[]; halfChecked: React.Key[] }) => {
    // 当返回的checkedKeys是一个对象时，提取checked数组
    const keys = Array.isArray(checkedKeys) ? checkedKeys : checkedKeys.checked;
    setSelectedUserIds(keys.map(key => key.toString()));
  };

  // 处理展开/折叠
  const handleExpand = async (newExpandedKeys: React.Key[], info: any) => {
    setExpandedKeys(newExpandedKeys);

    // 如果有传入加载子节点的函数，并且是展开操作
    if (onLoadChildren) {
      const nodeId = info.node.key.toString();

      // 检查是否正在加载中，避免重复加载
      if (loadingKeys.includes(nodeId)) return;

      // 检查节点是否已有子节点
      const foundNode = findNodeById(nodeId, userData);
      const hasLoadedChildren = foundNode?.children && foundNode.children.length > 0;
      if (!hasLoadedChildren) {
        try {
          setLoadingKeys(prev => [...prev, nodeId]);
          // 调用回调函数获取子节点
          const children = await onLoadChildren(nodeId);
          if (children && children.length > 0) {
            // 更新节点的子节点
            updateNodeChildren(nodeId, children);
          }
        } catch (error) {
          console.error('Failed to load children:', error);
        } finally {
          setLoadingKeys(prev => prev.filter(key => key !== nodeId));
        }
      }
    }
  };

  useEffect(() => {
    console.log(loadingKeys)
  }, [loadingKeys])

  // 在树中查找指定ID的节点
  const findNodeById = (id: string, nodes: SelectionItem[]): SelectionItem | undefined => {
    for (const node of nodes) {
      if (node.id === id) {
        return node;
      }
      if (node.children) {
        const found = findNodeById(id, node.children);
        if (found) return found;
      }
    }
    return undefined;
  };

  // 更新节点的子节点
  const updateNodeChildren = (nodeId: string, children: SelectionItem[]) => {
    const updateNodes = (nodes: SelectionItem[]): SelectionItem[] => {
      return nodes.map(node => {
        if (node.id === nodeId) {
          return { ...node, children };
        }
        if (node.children) {
          return { ...node, children: updateNodes(node.children) };
        }
        return node;
      });
    };

    setUserData(prev => updateNodes(prev));
  };

  // 处理移除选中项
  const handleRemoveItem = (key: React.Key) => {
    setSelectedUserIds(prev => prev.filter(k => k !== key.toString()));
  };

  // 获取选中的用户对象
  const getSelectedItems = () => {
    const result: SelectionItem[] = [];

    const findItemById = (id: string): SelectionItem | undefined => {
      const queue = [...userData];
      while (queue.length > 0) {
        const item = queue.shift()!;
        if (item.id === id) {
          return { ...item, children: undefined };
        }
        if (item.children) {
          queue.push(...item.children);
        }
      }
      return undefined;
    };

    selectedUserIds.forEach(id => {
      const item = findItemById(id);
      if (item) {
        result.push(item);
      }
    });

    return result;
  };

  // 用户选择下一步
  const handleUserSelectNext = () => {
    const selectedItems = getSelectedItems();
    setSelectedUsers(selectedItems);

    // 为新选择的用户初始化权限设置为'full'
    const newUserPermissions = { ...userPermissions };
    selectedItems.forEach(user => {
      if (!userPermissions[user.id]) {
        newUserPermissions[user.id] = 'full';
      }
    });
    setUserPermissions(newUserPermissions);

    // 进入权限设置步骤
    setCurrentStep(2);
  };

  // 处理单个用户的权限选择变化
  const handleUserPermissionChange = (userId: string, permission: string) => {
    setUserPermissions(prev => ({
      ...prev,
      [userId]: permission
    }));

    // 如果选择了"所有知识库可问答"，清空该用户的知识库选择
    if (permission === 'full') {
      setUserKnowledgeBases(prev => {
        const newState = { ...prev };
        delete newState[userId];
        return newState;
      });
    }
  };

  // 打开知识库选择模态框
  const handleEditKnowledgeBases = (userId: string) => {
    setCurrentEditingUserId(userId);
    // 设置当前选中的知识库
    setSelectedKbIds(userKnowledgeBases[userId] || []);
    setKbSelectVisible(true);
  };

  // 确认知识库选择
  const handleKbSelectConfirm = (kbs: SelectionItem[]) => {
    const kbIds = kbs.map(kb => kb.id);
    setUserKnowledgeBases(prev => ({
      ...prev,
      [currentEditingUserId]: kbIds
    }));
    setKbSelectVisible(false);
  };

  // 点击上一步，返回用户选择
  const handlePrevStep = () => {
    setCurrentStep(1);
  };

  // 完成设置，确认提交
  const handleFinish = () => {
    const usersWithPermissions: UserWithPermission[] = selectedUsers.map(user => ({
      ...user,
      permission: userPermissions[user.id] || 'full',
      allowedKnowledgeBases: userPermissions[user.id] === 'partial' ?
        userKnowledgeBases[user.id] || [] : []
    }));
    onConfirm(usersWithPermissions);
  };

  // 过滤树数据
  const filterTreeData = (data: DataNode[]): DataNode[] => {
    if (!searchValue) return data;

    const filterNodes = (nodes: DataNode[]): DataNode[] => {
      const result: DataNode[] = [];

      for (const node of nodes) {
        const nodeTitle = typeof node.title === 'string' ? node.title : '';
        const matchesSearch = nodeTitle.toLowerCase().includes(searchValue.toLowerCase());

        let filteredChildren: DataNode[] | undefined = undefined;
        if (node.children) {
          filteredChildren = filterNodes(node.children);
        }

        if (matchesSearch || (filteredChildren && filteredChildren.length > 0)) {
          result.push({
            ...node,
            children: filteredChildren,
          });
        }
      }

      return result;
    };

    return filterNodes(data);
  };

  // 树的渲染配置
  const treeData = filterTreeData(convertToTreeData(userData));

  // 已选择的用户列表
  const selectedItems = getSelectedItems();

  useEffect(() => {
    if (visible) {
      setCurrentStep(1)
    }
  }, [visible])

  const titleRender = (nodeData: DataNode) => {
    const isLoading = loadingKeys.includes(nodeData.key.toString());
    return (
      <div className="flex items-center" onClick={() => handleExpand([nodeData.key], { node: nodeData })}>
        <span>{nodeData.title}</span>
        {isLoading && (
          <Spin
            indicator={<LoadingOutlined style={{ fontSize: 16, marginLeft: 8 }} spin />}
            className="ml-2"
          />
        )}
      </div>
    );
  };

  return (
    <>
      <Modal
        title={currentStep === 1 ? "选择可见用户" : "问答权限设置"}
        open={visible}
        footer={null}
        onCancel={onCancel}
        width={640}
        styles={{ body: { padding: '5px' } }}
        maskClosable={false}
        centered
      >
        {currentStep === 1 ? (
          // 第一步：用户选择 - 不使用嵌套Modal
          <div>
            <div className="flex h-[300px] border border-[#C9CEE2] rounded-lg p-4">
              {/* 左侧搜索与用户列表 */}
              <div className="w-1/2 border-r border-[#C9CEE2] pr-4">
                <Input
                  placeholder="搜索用户名，部门，或用户"
                  prefix={<SearchOutlined style={{ color: '#C0C6CC' }} />}
                  className="mb-4"
                  value={searchValue}
                  onChange={handleSearchChange}
                />
                <div className="overflow-auto h-[220px]">
                  <Tree
                    checkable
                    checkStrictly={true}
                    checkedKeys={selectedUserIds}
                    // expandedKeys={expandedKeys}
                    onCheck={handleTreeSelect}
                    onExpand={handleExpand}
                    treeData={treeData}
                    switcherIcon={({ expanded }) => expanded ?
                      <CaretDownOutlined className="text-[#C0C6CC]" /> :
                      <CaretRightOutlined className="text-[#C0C6CC]" />}
                    blockNode
                    loadData={onLoadChildren ? async (node) => {
                      // 这里使用Tree组件的loadData方法，但主要逻辑在handleExpand中
                      return null;
                    } : undefined}
                    loadedKeys={loadingKeys}
                    titleRender={titleRender}
                  // titleRender={(nodeData) => (
                  //   <div onClick={() => handleExpand([nodeData.key], { node: nodeData })}>
                  //     {nodeData.title}
                  //   </div>
                  // )}
                  />
                </div>
              </div>

              {/* 右侧已选用户 */}
              <div className="w-1/2 pl-4">
                <div className="mb-4 text-[#86909C]">已选: {selectedItems.length} 个</div>
                <div className="overflow-auto h-[220px] panel-list">
                  <List
                    dataSource={selectedItems}
                    renderItem={item => (
                      <List.Item className="p-2 hover:bg-[#F5F7FA]">
                        <div className="flex justify-between w-full items-center">
                          <span>{item.name}</span>
                          <CloseOutlined
                            className="text-[#C0C6CC] cursor-pointer"
                            onClick={() => handleRemoveItem(item.id)}
                          />
                        </div>
                      </List.Item>
                    )}
                  />
                </div>
              </div>
            </div>

            {/* 底部按钮 */}
            <div className="flex justify-center items-center gap-10 mt-4">
              <Button
                shape="round"
                className="!h-11 w-32 !border-0 !bg-[#DFE1EB] !text-[#474C5F]"
                onClick={onCancel}
              >
                取消
              </Button>
              <Button
                type="primary"
                shape="round"
                className="ml-2 !h-11 w-32"
                onClick={handleUserSelectNext}
                disabled={selectedItems.length === 0}
              >
                下一步
              </Button>
            </div>
          </div>
        ) : (
          // 第二步：权限设置
          <>
            <div className="h-[300px] border border-[#C9CEE2] rounded-lg p-6">
              {/* 表格头部 */}
              <div className="flex w-full border-b border-[#E5E6EB]">
                <div className="w-1/3 text-[#1D2129] font-medium">用户组</div>
                <div className="w-2/3 text-[#1D2129] font-medium">权限</div>
              </div>

              {/* 表格内容 - 可滚动区域 */}
              <div className="overflow-auto max-h-[200px]">
                {selectedUsers.map((user, index) => (
                  <div key={user.id} className={`flex w-full py-3 ${index !== selectedUsers.length - 1 ? 'border-b border-[#E5E6EB]' : ''}`}>
                    <div className="w-1/3 text-[#4E5969] flex items-center">{user.name}</div>
                    <div className="w-2/3 flex items-center">
                      <Radio.Group
                        onChange={(e) => handleUserPermissionChange(user.id, e.target.value)}
                        value={userPermissions[user.id] || 'full'}
                        className="flex items-center"
                      >
                        <Radio value="full" className="mr-4">
                          <span className="text-[#4E5969]">所有知识库可问答</span>
                        </Radio>
                        <Radio value="partial">
                          <span className="text-[#4E5969]">部分知识库可问答</span>
                          {userPermissions[user.id] === 'partial' && (
                            <span
                              className="text-[#7B67EE] ml-1 text-xs cursor-pointer"
                              onClick={() => handleEditKnowledgeBases(user.id)}
                            >
                              编辑
                            </span>
                          )}
                        </Radio>
                      </Radio.Group>
                    </div>
                  </div>
                ))}
              </div>
            </div>
            {/* 底部按钮 */}
            <div className="flex justify-center mt-4 gap-10">
              <Button
                shape="round"
                className="!h-11 w-32 !border-0 !bg-[#DFE1EB] !text-[#474C5F]"
                onClick={handlePrevStep}
              >
                上一步
              </Button>
              <Button
                type="primary"
                shape="round"
                className="ml-2 !h-11 w-32"
                onClick={handleFinish}
              >
                完成
              </Button>
            </div>
          </>
        )}
      </Modal>

      {/* 知识库选择模态框 */}
      <KnowledgeBaseSelectModal
        title={`选择可回答的知识库`}
        visible={kbSelectVisible}
        knowledgeBases={knowledgeBases}
        selectedIds={selectedKbIds}
        onCancel={() => setKbSelectVisible(false)}
        onConfirm={handleKbSelectConfirm}
      />
    </>
  );
};

export default UserPermissionSelectModal; 